# 模型层
from django.db import models
# 引入官方插件的用户user模型
from django.contrib.auth.models import User
# 引入工具类的时间区间处理函数
from django.utils import timezone

# 定义商品类别
class Category(models.Model):
    # 这里定义模型的字段
    # 名称长度为100，
    name = models.CharField(max_length=100, verbose_name="类别名称")
    # 描述可以为空
    description = models.TextField(blank=True, verbose_name="类别描述")
    # 创建时间
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    # 当前模型的配置
    class Meta:
        # 表名称
        verbose_name = "商品类别"
        verbose_name_plural = "商品类别"
        # 排序字段
        ordering = ['name']

    # 如果需要将模型当做字符串使用，则返回模型名称，相当于php的__tostring方法
    def __str__(self):
        return self.name

# 商品模型
class Goods(models.Model):
    # 定义的表字段 这里每一个字段的类型都是从models中获取的
    name = models.CharField(max_length=200, verbose_name="商品名称")
    # 定义了封面图字段，存放路径
    cover_image = models.ImageField(upload_to='goods/covers/', verbose_name="封面图")
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="商品价格")
    stock = models.PositiveIntegerField(default=0, verbose_name="商品数量")
    # 定义模型关联
    categories = models.ManyToManyField(Category, related_name='goods', verbose_name="所属类别")
    description = models.TextField(verbose_name="商品描述")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    # 定义表名称，排序字段
    class Meta:
        verbose_name = "商品"
        verbose_name_plural = "商品"
        ordering = ['-created_at']

    def __str__(self):
        return self.name

class GoodsImage(models.Model):
    """商品详情图片模型（一对多：一个商品对应多张详情图）"""
    # 👇 添加外键，关联到 Goods，实现“一个商品对应多张详情图”
    goods = models.ForeignKey(Goods, on_delete=models.CASCADE, related_name='detail_images', verbose_name="关联商品")
    # 定义详情图片文件存放路径
    image = models.ImageField(upload_to='goods/details/', verbose_name="详情图片")
    # 创建时间
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        verbose_name = "商品详情图"
        verbose_name_plural = "商品详情图"

    def __str__(self):
        return f"{self.goods.name} 的详情图 {self.id}"

# 商品评论表
class Comment(models.Model):
    # 模型关联，和商品关联
    goods = models.ForeignKey(Goods, on_delete=models.CASCADE, related_name='comments', verbose_name="商品")
    # 和用户关联
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments', verbose_name="评论用户")
    content = models.TextField(verbose_name="评论内容")
    created_at = models.DateTimeField(default=timezone.now, verbose_name="评论时间")

    class Meta:
        verbose_name = "商品评论"
        verbose_name_plural = "商品评论"
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.user.username} 对 {self.goods.name} 的评论"